<?php
namespace app\admin\controller;

use app\admin\model\auser;
use think\Controller;
use think\Request;
use think\Session;
use think\Validate;

class Login extends Controller
{
    public function index()
    {
        if (Request::instance()->isPost()) {
            try {
                $post = input('post.');
                $rule = [
                    ['adname', 'require|length:1,20', '请输入用户名|用户名不能超过20个字符'],
                    ['password', 'require|length:6,12', '请输入密码|密码在6~10个字符'],
                    ['vercode', 'require', '请输入验证码'],
                ];
                $validate = new Validate($rule);
                if (!$validate->check($post)) throw new \Exception($validate->getError());

                //校验验证码
                if (!captcha_check($post['vercode'])) throw new \Exception('验证码错误');

                //获取用户
                $user = auser::where(['adname' => $post['adname']])->find();
                if (empty($user)) throw new \Exception('该用户名不存在');
                if (!$user['status']) throw new \Exception('用户已禁用');

                //校验密码
                if (!auser::checkPassword($post['password'], $user['salt'], $user['password'])) throw new \Exception('密码错误');

                //登录session
                auser::login($user);

                $json = ['code' => 200, 'msg' => 'success', 'session' => \think\Session::get('user', 'admin')];
            } catch (\Exception $e) {
                $json = ['code' => 400, 'msg' => $e->getMessage()];
            }
            return json($json);
        }

        if (Session::get('user', 'admin')) $this->redirect('admin/index');
        return $this->fetch();
    }

    public function logout()
    {
        auser::logout();

        $this->redirect('Login/index');
    }
}